package com.lintf.wxpay.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lintf.business.entity.OrderInfo;
import com.lintf.wxpay.base.WxChatPayDto;
import com.lintf.wxpay.base.enums.OrderStatus;
import com.lintf.wxpay.base.enums.WxPayType;
import com.lintf.wxpay.base.utils.OrderNoUtils;
import com.lintf.wxpay.mapper.OrderInfoMapper;
import com.lintf.wxpay.service.OrderInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.Instant;
import java.util.Date;
import java.util.List;

/**
 * @author lintf
 * @description 针对表【order_info】的数据库操作Service实现
 * @createDate 2024-11-21 14:20:27
 */
@Slf4j
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo>
        implements OrderInfoService {

    @Override
    public OrderInfo createOrder(WxChatPayDto dto, WxPayType wxPayType) {
        // 查询未支付订单
        log.info("正在查询未支付订单...");
        OrderInfo orderInfo = getNoPayOrderByProductId(dto.getProductId(), dto.getUserId());
        if (orderInfo != null) {
            log.info("存在未支付订单");
            return orderInfo;
        }
        // 生成订单
        log.info("正在生成订单...");
        orderInfo = new OrderInfo();
        orderInfo.setTitle(dto.getTitle())
                .setPrepayType(wxPayType.getType())
                .setOrderNo(OrderNoUtils.getOrderNo())
                .setProductId(dto.getProductId())
                .setUserId(dto.getUserId())
                .setTotalFee(new BigDecimal(dto.getTotalFee()))
                .setOrderStatus(OrderStatus.NOTPAY.getType())
                .setCreateTime(new Date())
                .setCreateTime(new Date());
        baseMapper.insert(orderInfo);
        log.info("已完成订单生成");
        return orderInfo;
    }

    @Override
    public List<OrderInfo> getNoPayOrderByDuration(int minutes) {
        Instant instant = Instant.now().minus(Duration.ofMinutes(minutes));

        LambdaQueryWrapper<OrderInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderInfo::getOrderStatus, OrderStatus.NOTPAY.getType())
                .le(OrderInfo::getCreateTime, instant);

        return baseMapper.selectList(wrapper);
    }

    private OrderInfo getNoPayOrderByProductId(Long productId, Long userId) {
        LambdaQueryWrapper<OrderInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderInfo::getProductId, productId)
                .eq(OrderInfo::getUserId, userId)
                .eq(OrderInfo::getOrderStatus, OrderStatus.NOTPAY.getType());
        return baseMapper.selectOne(wrapper);
    }
}




